<?php

// +----------------------------------------------------------------------
// | Banner 模型
// +----------------------------------------------------------------------
// | @author fancsen
// +----------------------------------------------------------------------

namespace app\api\model;

use app\api\model\BaseModel;

class Product extends BaseModel 
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'product';
    //自动时间戳
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_at';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    //隐藏字段
    protected $hidden = [
        'delete_time','update_time','from','category_id','create_time','pivot','img_id'
    ];

    public function imgs()
    {
        return $this->hasMany('ProductImage','product_id','id');
    }
    public function properties()
    {
        return $this->hasMany('ProductProperty','product_id','id');
    }

    public function getMainImgUrlAttr($value,$data)
    {
        return $this->prefixImgUrl($value,$data);
    }

    /**
     * 获取指定数目的最新商品
     */
    public  static function getRecentProducts($count)
    {
        $products = self::limit($count)->order('create_time,id desc')->select();

        return $products;
    }

    /**
     * 获取指定商品详情
     * @param $id 商品id
     */
    public static function getProductById($id)
    {
        $product = self::with(['imgs'=>function($query){
            $query->with(['imgUrl'])->order('sort','asc');
        },'properties'])
        ->find($id);

        return $product;
    }

}